<template>
  <div class="floating-population">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>流动人口管理</span>
          <el-button type="primary" @click="showInputDialog = true">
            <el-icon><Plus /></el-icon>
            录入流动人口
          </el-button>
        </div>
      </template>

      <!-- 查询区域 -->
      <div class="search-section">
        <el-form :model="searchForm" inline>
          <el-form-item label="姓名">
            <el-input v-model="searchForm.name" placeholder="请输入姓名" clearable style="width: 200px" />
          </el-form-item>
          <el-form-item label="身份证号">
            <el-input v-model="searchForm.idCard" placeholder="请输入身份证号" clearable style="width: 200px" />
          </el-form-item>
          <el-form-item label="居住类型">
            <el-select v-model="searchForm.residenceType" placeholder="请选择" clearable style="width: 160px">
              <el-option label="暂住" :value="1" />
              <el-option label="长期居住" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery" :loading="loading">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <el-table :data="tableData" v-loading="loading" border style="width: 100%">
        <el-table-column prop="name" label="姓名" min-width="120" />
        <el-table-column prop="idCard" label="身份证号" min-width="180" />
        <el-table-column label="居住类型" min-width="120">
          <template #default="scope">
            <el-tag :type="scope.row.residenceType === 1 ? 'warning' : 'success'">
              {{ scope.row.residenceType === 1 ? '暂住' : scope.row.residenceType === 2 ? '长期居住' : '-' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="currentAddress" label="现居住地址" min-width="200" />
        <el-table-column label="居住开始日期" min-width="140">
          <template #default="scope">
            {{ formatDate(scope.row.residenceStartDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="landlordName" label="房东姓名" min-width="120" />
        <el-table-column prop="landlordPhone" label="房东电话" min-width="140" />
        <el-table-column label="就业状况" min-width="120">
          <template #default="scope">
            <el-tag :type="employmentTagType(scope.row.employmentStatus)">
              {{ employmentLabel(scope.row.employmentStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="employerName" label="用工单位" min-width="160" />
        <el-table-column label="状态" min-width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? '在册' : '已注销' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <div class="action-buttons">
              <el-button type="primary" link @click="handleView(scope.row)">查看</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 录入对话框 -->
    <FloatingPopulationInput 
      v-model="showInputDialog"
      @success="handleInputSuccess"
    />
  </div>
 </template>

 <script setup>
 import { ref, reactive, onMounted } from 'vue'
 import { ElMessage } from 'element-plus'
 import { Plus, Search } from '@element-plus/icons-vue'
 import axios from 'axios'
 import { API_BASE_URL } from '@/config/api'
 import FloatingPopulationInput from './components/FloatingPopulationInput.vue'

 const loading = ref(false)
 const showInputDialog = ref(false)

 // 查询表单
 const searchForm = reactive({
   name: '',
   idCard: '',
   residenceType: null
 })

 // 表格数据
 const tableData = ref([])

 // 分页信息
 const pagination = reactive({
   currentPage: 1,
   pageSize: 10,
   total: 0
 })

 const employmentLabel = (status) => {
   switch (status) {
     case 1: return '就业'
     case 2: return '失业'
     case 3: return '学生'
     case 4: return '其他'
     default: return '-'
   }
 }

 const employmentTagType = (status) => {
   switch (status) {
     case 1: return 'success'
     case 2: return 'warning'
     case 3: return 'info'
     case 4: return ''
     default: return ''
   }
 }

 const formatDate = (date) => {
   if (!date) return ''
   try { return new Date(date).toLocaleDateString() } catch { return '' }
 }

 const loadData = async () => {
   loading.value = true
   try {
     const token = localStorage.getItem('token')
     if (!token) {
       ElMessage.error('请先登录')
       return
     }

     const params = {}
     if (searchForm.name && searchForm.name.trim()) params.name = searchForm.name.trim()
     if (searchForm.idCard && searchForm.idCard.trim()) params.idCard = searchForm.idCard.trim()
     if (searchForm.residenceType) params.residenceType = searchForm.residenceType
     // 必填分页参数
     params.pageNum = pagination.currentPage
     params.pageSize = pagination.pageSize

     const response = await axios.get(`${API_BASE_URL}/floatingPopulation/query`, {
       params,
       headers: { token }
     })

     const result = response.data
     if (result.status === 200) {
       tableData.value = result.data || []
       pagination.total = result.total ?? (result.data ? result.data.length : 0)
     } else {
       ElMessage.warning(result.msg || '查询接口暂未实现')
       tableData.value = []
       pagination.total = 0
     }
   } catch (error) {
     console.warn('查询流动人口数据失败或接口未实现:', error)
     ElMessage.info('查询接口待实现，暂不显示数据')
     tableData.value = []
     pagination.total = 0
   } finally {
     loading.value = false
   }
 }

 const handleQuery = () => {
   pagination.currentPage = 1
   loadData()
 }

 const resetQuery = () => {
   searchForm.name = ''
   searchForm.idCard = ''
   searchForm.residenceType = null
   pagination.currentPage = 1
   loadData()
 }

 const handleSizeChange = (size) => {
   pagination.pageSize = size
   // 页面大小变化后重置到第一页并重新查询
   pagination.currentPage = 1
   loadData()
 }

 const handleCurrentChange = (page) => {
   pagination.currentPage = page
   // 页码变化时重新查询
   loadData()
 }

 const handleView = (row) => {
   ElMessage.info('查看功能待开发')
 }

 const handleInputSuccess = () => {
   ElMessage.success('流动人口录入成功')
   loadData()
 }

 onMounted(() => {
   loadData()
 })
 </script>

 <style lang="scss" scoped>
 .floating-population {
   .card-header {
     display: flex;
     justify-content: space-between;
     align-items: center;
   }

   .search-section {
     margin-bottom: 16px;
   }

   .action-buttons {
     display: inline-flex;
     align-items: center;
     gap: 8px;
     white-space: nowrap;
   }

   .pagination-container {
     display: flex;
     justify-content: flex-end;
     margin-top: 12px;
   }
 }
 </style>